<template>
  <base-breadcrumb v-loading="loading">
    <a-card class="mb20">
      <titleName ref="box" title="基本信息" />
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-row :gutter="24">
            <a-col :md="16" :sm="16">
              <a-form-model-item label="所属单位：" prop="projectId">
                <org-tree-select
                        v-model="form.projectId"
                        placeholder="请选择"
                        :is-auto-select-first="this.$route.query.pageType === 'edit'?false:true"
                        check-strictly
                        is-need-auth
                        @select="selectOrg"
                        :is-query-projec-detail="false"
                />
              </a-form-model-item>
            </a-col>
<!--          <a-col :md="8" :sm="8">-->
<!--            <a-form-model-item label="分公司名称：" prop="branchComId">-->
<!--              <SelectSubCompany-->
<!--                v-model="form.branchComId"-->
<!--                placeholder="请选择"-->
<!--                :autoSelected="this.$route.query.pageType === 'edit'?false:true"-->
<!--                @selectChange="-->
<!--                  projectDeptOrgId = form.branchComId-->
<!--                  form.speaker = undefined-->
<!--                "-->
<!--              />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :md="8" :sm="8">-->
<!--            <a-form-model-item label="所属项目：" prop="projectId">-->
<!--              <SelectProject :autoSelected="false" :isPostpone="true" v-model="form.projectId" allowClear placeholder="请选择" :form="form" :is-edit="form.id !== null" key-value="branchComId" @change="changeProject" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
          <a-col :md="8" :sm="8">
            <a-form-model-item label="会议名称：" prop="meetingName">
              <BaseInput v-model.trim="form.meetingName" :max-length="30" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="会议类型：" prop="meetingKeyId">
              <BSelect
                v-model="form.meetingKeyId"
                :request="meetingTypeListReq"
                @selectChange="
                  form.meetingKeyName = $event.name
                  form.speaker = undefined
                "
              />
            </a-form-model-item>
          </a-col>
          <!--          <a-col :md="8" :sm="8">-->
          <!--            <a-form-model-item label="主持人/主讲人：" prop="speaker">-->
          <!--              &lt;!&ndash; <BaseInput :maxLength="30" placeholder="请输入" v-model.trim="form.speaker" /> &ndash;&gt;-->
          <!--              <SelectPersonByProject-->
          <!--                :id="form.branchCompanyId"-->
          <!--                v-model="form.speaker"-->
          <!--                :project-id="form.projectId"-->
          <!--                :show-search="true"-->
          <!--                mode="combobox"-->
          <!--                placeholder="请选择"-->
          <!--                option-label-prop="children"-->
          <!--              />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :md="8" :sm="8">
            <a-form-model-item label="主持人/主讲人：" prop="speaker">
              <ASelectOrgPeople v-model="form.speaker" :orgId="projectDeptOrgId" option-key="id" :init="false" :show-search="true" placeholder="请选择" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="会议地点：" prop="meetingPlace">
              <BaseInput v-model.trim="form.meetingPlace" :max-length="300" placeholder="请输入" />
            </a-form-model-item>
          </a-col>

          <a-col :md="8" :sm="8">
            <a-form-model-item label="会议时间：" prop="startTime">
              <a-date-picker v-model="form.startTime" :show-time="{ format: 'HH:mm' }" format="YYYY-MM-DD HH:mm" placeholder="请输入" @change="(date, dateString) => getTime(date, dateString, 'form', 'startTime')" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="教育课时：" prop="educationHour">
              <BaseInputNumber v-model="form.educationHour" :min="0" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="教育负责人：" prop="educationResponsible">
              <ASelectOrgPeople @onSelectChange="form.educationResponsibleId = $event.name" v-model="form.educationResponsible" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="受教育单位：" prop="educationOrganization">
              <BaseTextarea v-model="form.educationOrganization" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card class="mb20">
      <a-form-model :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-model-item label="参会者选择：" prop="meetingEmployeeDTOList">
              <div class="mb12">
                <a-button icon="plus" class="btn_right" type="primary" @click="openSelectPersonModal"> 添加人员 </a-button>
                <a-button :disabled="rowSelection.selectedRowKeys.length < 1" icon="delete" type="danger" @click="handleRemoveMore"> 移除 </a-button>
              </div>
              <!-- 统计选中项 -->
              <a-alert :show-icon="true">
                <template slot="message">
                  <span style="margin-right: 12px">
                    已选择:
                    <a>
                      <b>{{ rowSelection.selectedRowKeys.length }}</b>
                    </a>
                    项
                  </span>
                </template>
              </a-alert>
              <!-- 表格 -->
              <s-table
                ref="tableEmployee"
                table-layout="fixed"
                size="default"
                row-key="id"
                :columns="columnsEmployee"
                :data="loadDataEmployee"
                :alert="true"
                :row-selection="rowSelection"
                show-size-changer
                show-quick-jumper
                show-pagination="auto"
              >
                <!-- 表格行操作栏 -->
                <span slot="actions" slot-scope="text, record, index">
                  <template>
                    <a @click="handleRemove(index)">移除</a>
                  </template>
                </span>
              </s-table>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>

    <div class="tool-btns page-btn-right-top">
      <a-button class="ml20" :loading="loading" type="primary" @click="addMeeting">提交</a-button>
      <a-button class="ml20" type="primary" @click="handleClose">关闭</a-button>
    </div>

    <!-- 表单弹窗 -->
    <dialog-edit ref="dialogEdit" :meeting-employee-d-t-o-list-data="form.meetingEmployeeDTOListData" :visible.sync="visible" @confirm="submitForm" @confirms="submitForms" />
    <SelectPerson ref="SelectPersonWithTree" headerTitle="添加参会人员" :unRepeatPerson="true" @confirm="submitForms" />
  </base-breadcrumb>
</template>
<script>
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'

const columnsEmployee = [
  {
    title: '员工名称',
    dataIndex: 'name'
  },

  {
    title: '电话号码',
    dataIndex: 'phone'
  },

  {
    title: '操作',
    dataIndex: 'actions',
    width: '100px',
    scopedSlots: { customRender: 'actions' }
  }
]
const columns = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '5%',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '文件名称',
    dataIndex: 'fileName',
    width: '40%'
  },
  {
    title: '文件格式',
    dataIndex: 'suffixName'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '10%',
    scopedSlots: { customRender: 'action' }
  }
]
import meetingTypeApi from '@/api/safetySupervision/base/meetingType.js'

import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
import { STable } from '@/components'
import dialogEdit from '@/views/conference/standardConference/conferenceList/dialogEdit.vue'
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import SelectPerson from '@/components/BComponents/BSelectPerson'
import { getMeetingType, addMeeting, getConstructionProgram, getReviewPlan, getDisclosurePlan, getMeeting, editMeeting } from '@/api/office/conference'
import Vue from 'vue'

export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    STable,
    SelectSubcontractor,
    SelectPersonByProject,
    dialogEdit,
    SelectPerson,
    ASelectOrgPeople
  },
  data() {
    return {
      meetingTypeListReq: async () => {
        let res = await meetingTypeApi.list({}, { pageNo: 1, pageSize: 1000, query: { type: 13, enable: true } })
        if (res.code === this.SUCCESS_CODE) {
          res.data = res.data.filter((v) => {
            return v.enabled === 'TRUE'
          })
          return { code: 200, data: res.data }
        }
        return { code: 200, data: [] }
      },
      columns,
      columnsEmployee,
      meetingType: false,
      token: Vue.getAcloudProvider().getAccessToken(),
      form: {
        id: null,
        educationHour: '',
        educationResponsible: '',
        educationOrganization: '',
        value: 1,
        speaker: '',
        meetingSummary: '',
        fileList: [],
        meetingEmployeeDTOList: [],
        meetingEmployeeDTOListData: [],
        branchComId: '',
        projectId: '',
        name: '',
        meetingName: '',

        startTime: '',
        meetingExplains: '',
        commentedPlan: '',
        programmer: '',
        otherReviewer: '',
        professionComName: '',
        hsemonth: '',
        currentConstructionStage: '',
        meetingCount: '',
        mainParticipants: ''
      },
      rules: {
        meetingKeyId: [{ required: true, message: '请选择会议类型' }],
        month: [{ required: true, message: '请选择月份' }],
        commentedPlan: [{ required: true, message: '请选择交底方案', trigger: 'blur' }],
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'blur' }],

        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        meetingName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        speaker: [{ required: true, message: '请输入主持人/主讲人', trigger: 'blur' }],
        meetingPlace: [{ required: true, message: '请输入会议地点', trigger: 'blur' }],
        startTime: [{ required: true, message: '请输入会议时间', trigger: 'change' }],
        educationHour: [{ required: true, message: '请输入教育课时', trigger: 'blur' }],
        educationOrganization: [{ required: true, message: '请输入受教育单位', trigger: 'blur' }],
        educationResponsible: [{ required: true, message: '请选择教育负责人', trigger: 'change' }],
        meetingExplains: [{ required: true, message: '请输入会议说明', trigger: 'blur' }]
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.fileList
          })
        })
      },
      loadDataEmployee: (parameter) => {
        return new Promise((resolve, reject) => {
          let obj = {}
          obj.currentPage = parameter.pageNo
          obj.pageSize = parameter.pageSize
          obj.totalPage = Math.ceil(this.form.meetingEmployeeDTOListData.length / parameter.pageSize)
          obj.totalSize = this.form.meetingEmployeeDTOListData.length
          obj.data = this.form.meetingEmployeeDTOListData || []
          console.log(obj)
          resolve(obj)
        })
      },
      loading: false,
      id: '',
      isUpdate: true,
      meetingTypeList: [], //会议类别
      constructionProgram: [],
      reviewPlan: [],
      disclosurePlan: [],
      visible: false,
      // 表格复选框配置
      rowSelection: {
        selectedRowKeys: [],
        onChange(selectedRowKeys) {
          this.selectedRowKeys = selectedRowKeys
        }
      },
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象
      projectDeptOrgId: '' //项目所在的树节点Id
    }
  },
  mounted() {

    this.getMeetingType()

    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      this.getData()
    }
    if (this.$route.query.typeId) {
      this.form.value = this.$route.query.typeId
    }
  },
  methods: {
    async getData() {
      this.loading = true
      const [err, res] = await getMeeting({ id: this.form.id })
      this.loading = false
      if (!err) {
        this.form = { ...this.form, ...res.data }
        this.form.meetingEmployeeDTOListData = this.$clone(this.form.meetingEmployeeVOList)
        this.form.meetingEmployeeDTOListData.map((v) => (v.id = v.userId))
        this.$refs.tableEmployee.refresh(true)
        // if (this.form.projectId) {
        //   this.getProjectInfo(this.form.projectId)
        // }
      }
    },
    async getMeetingType() {
      const [err, res] = await getMeetingType()
      if (!err) {
        this.meetingTypeList = res.data
          .filter((v) => v.id !== '648785280249237505')
          .map((item) => {
            item.value = item.category
            item.label = item.name
            return item
          })
        console.log(this.meetingTypeList)
      }
    },
    openSelectPersonModal() {
      const list = this.form.meetingEmployeeDTOListData
      this.$refs.SelectPersonWithTree.open(list)
    },
    // 提交表单
    submitForm(e) {
      this.form.meetingEmployeeDTOListData.push(e)
      console.log(this.form.meetingEmployeeDTOListData)
      this.$refs.tableEmployee.refresh(true)
    },
    submitForms(e) {
      e.forEach((item) => {
        this.form.meetingEmployeeDTOListData.push(item)
      })
    },
    handleRemove(index) {
      this.form.meetingEmployeeDTOListData.splice(index, 1)
      this.$refs.tableEmployee.refresh(true)
    },
    // 移除表格选中项
    handleRemoveMore() {
      // 若有选中项
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确定移除这些数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log(that.rowSelection.selectedRowKeys)
          for (let index = 0; index < that.form.meetingEmployeeDTOListData.length; index++) {
            let item = that.form.meetingEmployeeDTOListData[index]
            console.log(index, item.id)
            if (that.rowSelection.selectedRowKeys.includes(item.id)) {
              that.form.meetingEmployeeDTOListData.splice(index, 1)
              index--
            }
          }
          that.$refs.tableEmployee.clearSelected()
          that.$refs.tableEmployee.refresh(true)
          // console.log(that.rowSelection.selectedRowKeys)
        }
      })
    },
    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
      this.form.speaker = ''
      this.getProjectInfo(this.form.projectId)
    },

    getProjectInfo(id) {
      getProjectInfo({ projectId: id }).then((res) => {
        this.projectDeptOrgId = res.data.projectDeptOrgId
        // this.form.meetingEmployeeDTOListData = []
        // this.$refs.tableEmployee?.refresh(true)
        console.log(res)
      })
    },
    // changeProject(e) {
    //   this.form.speaker = ''
    //   if (e) this.getProjectInfo(e)
    // },
    getTime(date, dateString, type, name) {
      this[type][name] = dateString
      console.log(this[type][name])
    },
    delItem(idx) {
      this.form.fileList.splice(idx, 1)
      this.$refs.table.refresh(true)
      console.log(this.form.fileList)
    },
    fileArrysData: function (val) {
      this.form.fileList = val
      this.$refs.table.refresh(true)
    },

    onChangeRadio(e) {
      console.log(e)
    },
    onChange(e) {
      console.log(e)
      // this.form.value = e.target.value
    },
    onSelectChange(e) {
      console.log('selectedRowKeys changed: ', e)
    },
    commentsVal: function (val) {
      console.log(val)
      this.form.meetingSummary = val
    },
    handleClose() {
      this.$multiTab.close(this.$route.fullpath)
      //  history.go(-1)
    },
    //基本会议
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((valid) => {
        flag = valid
        if(!valid) {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    //施工方案评审会议
    validateFormRule(rule) {
      let flagrule = true
      let flagbasis = false

      if (rule == 4 || rule == 6) {
        flagbasis = this.validateForm()
        return flagbasis
      } else {
        flagbasis = this.validateForm()
      }
      if (rule == 9) {
        rule = 8
      }
      let ruleForm = 'ruleForm' + rule
      console.log(ruleForm)
      this.$refs[ruleForm].validate((valid) => {
        flagrule = valid
      })

      if (flagrule && flagbasis) {
        return true
      } else {
        this.$message.warning('表单填写不完整')
        return false
      }
    },
    async addMeeting() {
      this.$console(this.form)
      const rule = this.form.value
      if (!this.validateForm()) return
      if (rule == 8 || rule == 9) {
        if (this.form.meetingSummary == '') {
          this.$message.warning('请填写会议纪要')
          return
        }
      } else {
        if (this.form.meetingEmployeeDTOListData.length == 0) {
          this.$message.warning('请选择参会人员')
          return
        }
      }
      this.form.meetingEmployeeDTOList = []
      this.form.meetingEmployeeDTOListData.forEach((item) => {
        this.form.meetingEmployeeDTOList.push(item.id)
      })
      const params = {
        ...this.form,
        meetingTypeId: this.meetingTypeList.filter((item) => this.form.value == item.category)[0].id
      }

      this.loading = true
      let err
      let res
      if (params.id) {
        ;[err, res] = await editMeeting(params)
      } else {
        ;[err, res] = await addMeeting(params)
      }
      this.loading = false
      if (!err) {
        this.$message.success('操作成功')
        this.handleClose()
      }
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;

  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}

.row {
  display: flex;
  flex-direction: row;
}
</style>
